use std::cell::RefCell;
use std::fs::File;
use std::io::Read;

use crate::class_file_packet::ClassFilePacket;

pub struct JarClassFilePacket {
    pub jar_file_path: RefCell<String>,
}


impl ClassFilePacket for JarClassFilePacket {
    fn read_class(&self, class_name: &String) -> Result<Vec<u8>, String> {
        let class_file_path = format!("{}.class", class_name);
        let zip_file = File::open(self.jar_file_path.take()).unwrap();
        let mut zip_archive = zip::ZipArchive::new(zip_file).unwrap();

        for index in 0..zip_archive.len() {
            let mut file = zip_archive.by_index(index).unwrap();
            if class_file_path.as_str().eq(file.name()) {
                let mut data: Vec<u8> = Vec::new();
                let result = file.read_to_end(&mut data);
                match result {
                    Ok(_size) => {
                        return Ok(data);
                    }
                    Err(err) => {
                        println!("err:{}", err);
                        return Err(String::from("Class Not Found"));
                    }
                }
            }
        }
        return Err(String::from("Class Not Found"));
    }

    fn to_string(&self) -> String {
        return format!("JarFileClassFilePacket[{}]", self.jar_file_path.borrow());
    }
}